import java.util.ArrayList;
import java.util.List;

public class RSICalculator {

    // 计算移动平均（简单移动平均示例，可根据需要替换为更复杂的移动平均算法）
    private static double calculateSMA(List<Double> data, int period) {
        double sum = 0;
        for (Double value : data) {
            sum += value;
        }
        return sum / period;
    }

    // 计算RSI指标
    public static double[] calculateRSI(double[] closePrices, int[] periods) {
        double[] rsiValues = new double[periods.length];

        for (int pIndex = 0; pIndex < periods.length; pIndex++) {
            int period = periods[pIndex];
            List<Double> upMoves = new ArrayList<>();
            List<Double> downMoves = new ArrayList<>();

            // 第一步：计算每日的上涨幅度和下跌幅度
            for (int i = 1; i < closePrices.length; i++) {
                double change = closePrices[i] - closePrices[i - 1];
                if (change > 0) {
                    upMoves.add(change);
                    downMoves.add(0.0);
                } else {
                    upMoves.add(0.0);
                    downMoves.add(Math.abs(change));
                }
            }

            // 第二步：计算上涨幅度和下跌幅度的移动平均值
            List<Double> smaUpMoves = new ArrayList<>();
            List<Double> smaDownMoves = new ArrayList<>();
            for (int j = period - 1; j < upMoves.size(); j++) {
                List<Double> upPeriod = upMoves.subList(j - period + 1, j + 1);
                List<Double> downPeriod = downMoves.subList(j - period + 1, j + 1);
                smaUpMoves.add(calculateSMA(upPeriod, period));
                smaDownMoves.add(calculateSMA(downPeriod, period));
            }

            // 第三步：计算RSI值
            for (int k = 0; k < smaUpMoves.size(); k++) {
                double smaUp = smaUpMoves.get(k);
                double smaDown = smaDownMoves.get(k);
                rsiValues[pIndex] = (smaUp / (smaUp + smaDown)) * 100;
            }
        }

        return rsiValues;
    }

    public static void main(String[] args) {
        // 示例收盘价数据
        double[] closePrices = {4.27, 4.36, 4.25, 4.47, 4.44, 4.38, 4.82};
        // 计算周期，这里示例设置两个常见周期
        int[] periods = {6, 12};

        double[] rsiResults = calculateRSI(closePrices, periods);

        for (int i = 0; i < rsiResults.length; i++) {
            System.out.println("RSI for period " + periods[i] + ": " + rsiResults[i]);
        }
    }
}